package com.sky.loveshop.controller;

import cn.hutool.core.date.DateUtil;
import com.sky.loveshop.entity.Product;
import com.sky.loveshop.entity.Result;
import com.sky.loveshop.entity.common.PageResult;
import com.sky.loveshop.entity.exception.BizException;
import com.sky.loveshop.entity.exception.BizExceptionEnum;
import com.sky.loveshop.entity.qo.ProductQO;
import com.sky.loveshop.entity.vo.ProductVO;
import com.sky.loveshop.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;

/**
 * @author xcy
 * @version V1.0
 * @description
 * @date 2024/8/18 0:04
 */
@Slf4j
@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;
    @Value("${file.save-place}")
    private String fileSavePlace;

    @PostMapping("/listProductPages")
    public Result<PageResult<ProductVO>> listProductPages(@RequestBody ProductQO productQO) {
        return Result.page(productService.listProductPages(productQO));
    }

    @PostMapping("/listProduct")
    public Result<List<ProductVO>> listProduct(@RequestBody ProductQO productQO) {
        return Result.success(productService.listProduct(productQO));
    }

    @PutMapping("/addProduct")
    public Result<Integer> addProduct(@RequestBody @Valid Product product) {
        return Result.success(productService.addProduct(product));
    }

    @DeleteMapping("/delProductById")
    public Result<Integer> delProductById(Integer id) throws BizException {
        if (id == null) {
            throw new BizException(BizExceptionEnum.ID_MUST_NEED);
        }
        return Result.success(productService.delProductById(id));
    }

    @PostMapping("/editProduct")
    public Result<Integer> editProduct(@RequestBody Product product) throws BizException {
        if (product.getId() == null) {
            throw new BizException(BizExceptionEnum.ID_MUST_NEED);
        }
        return Result.success(productService.updateProductById(product));
    }

    @GetMapping("/getProductById")
    public Result<ProductVO> getProductById(Integer id) throws BizException {
        if (id == null) {
            throw new BizException(BizExceptionEnum.ID_MUST_NEED);
        }
        return Result.success(productService.getProductById(id));
    }

    @PostMapping("/upload")
    public Result<String> handleFileUpload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new BizException(BizExceptionEnum.PICTURE_MUST_NOT_NULL);
        }
        String originalFilename = file.getOriginalFilename();
        String name = originalFilename.split("\\.")[0];
        String type = originalFilename.split("\\.")[1];
        String newName = name + DateUtil.now().replace(" ", "-").replace(":", "-") + "." + type;
        // 拼接文件保存路径
        String filePath = fileSavePlace + newName;
        // 将文件保存到磁盘
        file.transferTo(new File(filePath));
        return Result.success(newName);
    }

    @GetMapping("/image/{fileName}")
    public ResponseEntity<byte[]> getImage(@PathVariable("fileName") String fileName) throws BizException {
        // 构建图片路径
        String filePath = fileSavePlace + fileName;
        File imageFile = new File(filePath);
        try {
            // 读取图片文件并返回
            byte[] imageBytes = Files.readAllBytes(imageFile.toPath());
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_JPEG);
            return new ResponseEntity<>(imageBytes, headers, HttpStatus.OK);
        } catch (IOException e) {
            log.error("getImageError 获取图片异常", e);
            e.printStackTrace();
            throw new BizException(BizExceptionEnum.FILE_NOT_FOUND);
        }
    }

}
